import { ref, onUnmounted } from 'vue'
import { EventSourcePolyfill } from 'event-source-polyfill'
import DEFAULT_CONFIG from '@/config/index.js'

/**
 * SSE 聊天组合函数
 * 对接接口格式: http://localhost:1818/hello/stream/chat2?query=xxx&chat-id=xxx
 */
const buildSSEHeaders = () => {
  const extraHeaders = { ...(DEFAULT_CONFIG.HEADERS || {}) }
  const token = localStorage.getItem('token')
  if (token) {
    const tokenName = DEFAULT_CONFIG.TOKEN_NAME || 'Authorization'
    const tokenPrefix = DEFAULT_CONFIG.TOKEN_PREFIX ?? ''
    const normalizedPrefix = typeof tokenPrefix === 'string' ? tokenPrefix : ''
    const normalizedToken = (() => {
      if (!normalizedPrefix) {
        return token
      }
      const trimmedPrefix = normalizedPrefix.trim()
      if (trimmedPrefix && (token.startsWith(normalizedPrefix) || token.startsWith(trimmedPrefix))) {
        return token
      }
      return `${normalizedPrefix}${token}`
    })()
    extraHeaders[tokenName] = normalizedToken
  }
  return Object.keys(extraHeaders).length > 0 ? extraHeaders : null
}

const createAuthorizedEventSource = (url) => {
  const headers = buildSSEHeaders()
  if (headers) {
    return new EventSourcePolyfill(url, {
      headers
    })
  }
  return new EventSourcePolyfill(url)
}

export function createSSEChat() {
  const connected = ref(false)
  const loading = ref(false)
  let eventSource = null
  let currentChatId = ref(null)
  let timeoutId = null

  const messages = ref([
    {
      id: Date.now(),
      role: 'assistant',
      content: '你好！我是AI助手，有什么可以帮你的吗？',
      timestamp: Date.now()
    }
  ])

  // 获取SSE接口地址
  const getSSEBaseUrl = () => {
    try {
      const aiSettings = localStorage.getItem('aiSettings')
      if (aiSettings) {
        const config = JSON.parse(aiSettings)
        if (config.sseUrl) {
          return config.sseUrl
        }
      }
    } catch (error) {
      console.error('加载AI设置失败:', error)
    }
    // 默认使用 localhost:1818
    return DEFAULT_CONFIG.REMOTE_URL || 'http://localhost:1818'
  }

  // 关闭当前连接
  const closeConnection = () => {
    // 清除超时定时器
    if (timeoutId) {
      clearTimeout(timeoutId)
      timeoutId = null
    }
    if (eventSource) {
      eventSource.close()
      eventSource = null
      connected.value = false
    }
  }

  // 发送消息（通过SSE）
  const sendMessage = (message, chatId = null) => {
    if (!message || !message.trim()) {
      return
    }

    // 如果正在加载，不允许发送新消息
    if (loading.value) {
      console.warn('正在处理消息，请稍候...')
      return
    }

    // 关闭之前的连接
    closeConnection()

    // 添加用户消息到消息列表
    messages.value.push({
      id: Date.now(),
      role: 'user',
      content: message.trim(),
      timestamp: Date.now(),
      isNew: true
    })

    // 500ms 后移除 isNew 标记（动画完成后）
    setTimeout(() => {
      const lastMsg = messages.value[messages.value.length - 1]
      if (lastMsg && lastMsg.role === 'user') {
        delete lastMsg.isNew
      }
    }, 500)

    // 设置加载状态
    loading.value = true

    // 如果没有提供 chatId，使用当前 chatId 或生成新的
    if (!chatId) {
      chatId = currentChatId.value || Date.now().toString()
      currentChatId.value = chatId
    } else {
      currentChatId.value = chatId
    }

    // 构建SSE URL
    const baseUrl = getSSEBaseUrl()
    const query = encodeURIComponent(message.trim())
    const sseUrl = `${baseUrl}/hello/stream/chat2?query=${query}&chat-id=${chatId}`

    console.log('连接SSE:', sseUrl)

    try {
      // 创建新的助手消息（用于流式接收）
      const assistantMessage = {
        id: Date.now(),
        role: 'assistant',
        content: '',
        timestamp: Date.now(),
        isNew: true
      }
      messages.value.push(assistantMessage)

      // 流式接收完成后移除 isNew 标记
      const removeNewFlag = () => {
        setTimeout(() => {
          if (assistantMessage) {
            delete assistantMessage.isNew
            // 触发响应式更新
            messages.value = [...messages.value]
          }
        }, 500)
      }

      // 创建 EventSource 连接
      eventSource = createAuthorizedEventSource(sseUrl)

      // 连接打开
      eventSource.onopen = () => {
        console.log('SSE连接已建立')
        connected.value = true
      }

      // 接收消息
      eventSource.onmessage = (event) => {
        try {
          let data = event.data

          // 如果数据为空，跳过
          if (!data || data.trim() === '') {
            return
          }

          // SSE 数据格式可能是 "data: xxx" 格式，需要提取实际内容
          if (data.startsWith('data: ')) {
            data = data.substring(6) // 移除 "data: " 前缀
          }

          // 尝试解析JSON
          let parsedData = null
          try {
            parsedData = JSON.parse(data)
          } catch (e) {
            // 如果不是JSON，直接作为文本内容处理
            parsedData = null
          }

          // 获取最后的助手消息
          const lastMsg = messages.value[messages.value.length - 1]
          if (!lastMsg || lastMsg.role !== 'assistant') {
            return
          }

          // 处理不同类型的消息
          if (parsedData) {
            // 处理JSON格式的消息
            if (parsedData.content !== undefined) {
              lastMsg.content += parsedData.content || ''
            } else if (parsedData.messageType) {
              // 处理结构化消息
              handleStructuredMessage(parsedData, lastMsg, removeNewFlag)
            } else if (parsedData.text) {
              lastMsg.content += parsedData.text || ''
            } else if (parsedData.message) {
              lastMsg.content += parsedData.message || ''
            } else {
              // 如果JSON中没有明确的内容字段，尝试使用整个数据
              lastMsg.content += data
            }
          } else {
            // 直接作为文本内容追加
            lastMsg.content += data
          }

          // 触发响应式更新（确保 Vue 能检测到内容变化）
          messages.value = [...messages.value]
        } catch (error) {
          console.error('处理SSE消息失败:', error)
        }
      }

      // 处理错误
      eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        connected.value = false
        loading.value = false

        // 清除超时定时器
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }

        // 如果连接关闭，添加错误消息
        if (eventSource && eventSource.readyState === EventSource.CLOSED) {
          const lastMsg = messages.value[messages.value.length - 1]
          if (lastMsg && lastMsg.role === 'assistant' && !lastMsg.content) {
            lastMsg.content = '连接已关闭，请重试'
            lastMsg.isError = true
          } else if (!lastMsg || lastMsg.role !== 'assistant') {
            messages.value.push({
              id: Date.now(),
              role: 'assistant',
              content: '连接错误，请重试',
              timestamp: Date.now(),
              isError: true
            })
          }
        }

        // 关闭连接
        closeConnection()
      }

      // 监听自定义事件（如果服务器发送了特定事件类型）
      eventSource.addEventListener('end', (event) => {
        console.log('SSE流结束', event)
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }
        loading.value = false
        removeNewFlag()
        closeConnection()
      })

      eventSource.addEventListener('close', (event) => {
        console.log('SSE连接关闭', event)
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }
        loading.value = false
        removeNewFlag()
        closeConnection()
      })

      eventSource.addEventListener('error', (event) => {
        console.error('SSE错误事件:', event)
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }
        loading.value = false
        const lastMsg = messages.value[messages.value.length - 1]
        if (lastMsg && lastMsg.role === 'assistant') {
          if (!lastMsg.content) {
            lastMsg.content = `错误：${event.data || '连接错误'}`
            lastMsg.isError = true
          }
        }
        removeNewFlag()
        closeConnection()
      })

      // 设置超时，如果60秒没有收到结束信号，自动关闭
      timeoutId = setTimeout(() => {
        if (loading.value && eventSource) {
          console.warn('SSE连接超时，自动关闭')
          loading.value = false
          const lastMsg = messages.value[messages.value.length - 1]
          if (lastMsg && lastMsg.role === 'assistant' && !lastMsg.content.trim()) {
            lastMsg.content = '响应超时，请重试'
            lastMsg.isError = true
          }
          removeNewFlag()
          closeConnection()
        }
      }, 60000)

    } catch (error) {
      console.error('创建SSE连接失败:', error)
      loading.value = false
      connected.value = false
      messages.value.push({
        id: Date.now(),
        role: 'assistant',
        content: `连接失败：${error.message}`,
        timestamp: Date.now(),
        isError: true
      })
    }
  }

  // 处理结构化消息
  const handleStructuredMessage = (parsedData, assistantMessage, removeNewFlag) => {
    const { messageType, content, error } = parsedData

    switch (messageType) {
      case 'content':
        if (content && content !== '') {
          assistantMessage.content += content || ''
        }
        break
      case 'reasoning':
        // 推理消息可以单独处理，这里暂时合并到内容中
        if (content && content !== '') {
          assistantMessage.content += content || ''
        }
        break
      case 'over':
      case 'end':
        console.log('消息接收完成')
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }
        loading.value = false
        if (removeNewFlag) removeNewFlag()
        closeConnection()
        break
      case 'error':
        console.error('接收到错误消息:', error)
        if (timeoutId) {
          clearTimeout(timeoutId)
          timeoutId = null
        }
        loading.value = false
        assistantMessage.content = `错误：${error || '未知错误'}`
        assistantMessage.isError = true
        if (removeNewFlag) removeNewFlag()
        closeConnection()
        break
      default:
        // 其他类型，尝试提取内容
        if (content) {
          assistantMessage.content += content
        }
    }
  }

  // 手动重连（SSE不支持重连，需要重新发送消息）
  const reconnect = () => {
    console.log('SSE不支持重连，请重新发送消息')
    closeConnection()
    connected.value = false
  }

  // 获取连接状态
  const getConnectionStatus = () => {
    if (!eventSource) return 'disconnected'
    switch (eventSource.readyState) {
      case EventSource.CONNECTING: return 'connecting'
      case EventSource.OPEN: return 'connected'
      case EventSource.CLOSED: return 'disconnected'
      default: return 'unknown'
    }
  }

  // 清空消息历史
  const clearMessages = () => {
    messages.value = [{
      id: Date.now(),
      role: 'assistant',
      content: '你好！我是AI助手，有什么可以帮你的吗？',
      timestamp: Date.now()
    }]
    currentChatId.value = null
  }

  // 删除指定消息
  const deleteMessage = (messageId) => {
    messages.value = messages.value.filter(msg => msg.id !== messageId)
  }

  // 重新发送消息
  const resendMessage = (messageId) => {
    const message = messages.value.find(msg => msg.id === messageId)
    if (message && message.role === 'user') {
      // 删除该消息及其后的所有消息
      const index = messages.value.findIndex(msg => msg.id === messageId)
      if (index !== -1) {
        messages.value = messages.value.slice(0, index)
        // 重新发送
        sendMessage(message.content, currentChatId.value)
      }
    }
  }

  // 导出对话历史
  const exportHistory = () => {
    return JSON.stringify(messages.value, null, 2)
  }

  // 导入对话历史
  const importHistory = (historyJson) => {
    try {
      const history = JSON.parse(historyJson)
      if (Array.isArray(history)) {
        messages.value = history
      }
    } catch (error) {
      console.error('导入历史失败:', error)
      throw error
    }
  }

  // 获取消息统计
  const getMessageStats = () => {
    const stats = {
      total: messages.value.length,
      user: messages.value.filter(msg => msg.role === 'user').length,
      assistant: messages.value.filter(msg => msg.role === 'assistant').length
    }
    return stats
  }

  // 设置当前聊天ID
  const setChatId = (chatId) => {
    currentChatId.value = chatId
  }

  // 获取当前聊天ID
  const getChatId = () => {
    return currentChatId.value
  }

  // 设置消息列表（用于切换对话时）
  const setMessages = (newMessages) => {
    if (Array.isArray(newMessages)) {
      // 深拷贝避免引用问题
      messages.value = JSON.parse(JSON.stringify(newMessages))
    }
  }

  // 组件卸载时清理
  onUnmounted(() => {
    closeConnection()
  })

  return {
    sendMessage,
    connected,
    messages,
    loading,
    reconnect,
    getConnectionStatus,
    clearMessages,
    deleteMessage,
    resendMessage,
    exportHistory,
    importHistory,
    getMessageStats,
    setChatId,
    getChatId,
    closeConnection,
    setMessages
  }
}

